package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.Relation;
import com.mbyte.easy.admin.service.IAllotService;
import com.mbyte.easy.admin.service.IRelationService;
import com.mbyte.easy.common.constant.roleCommonEntity;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysRole;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.entity.SysUserRoles;
import com.mbyte.easy.security.mapper.SysUserRolesMapper;
import com.mbyte.easy.security.service.IRoleService;
import com.mbyte.easy.security.service.IUserService;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @ClassName roleController
 * @Description: 员工分配
 * @Author:白章荣
 * @Date : 2019/12/18/10:05
 */
@Slf4j
@Controller
@RequestMapping("/admin/EveryRoleController")
public class EveryRoleController {

    @Autowired
    private IRelationService relationService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IAllotService allotService;
    @Autowired
    private SysUserRolesMapper userRolesMapper;


    private String prefix = "admin/role/";

    /**
     * 根据登录者的角色返回下属的角色
     *
     * @return
     */
    @RequestMapping("findAllRole")
    public String findAllRole(Model model, @RequestParam("userId") String userId) {
        log.info("userId======"+userId);
        SysUserRoles roleIdByUserId = userRolesMapper.findRoleIdByUserId(Long.valueOf(userId));
        log.info("==========roleIdByUserId"+roleIdByUserId.getRolesId());
        Set<Long> subordinateRoleByLoginId = findPeopleByRoleId(roleIdByUserId.getRolesId());
        log.info("==============获取到的set集合为======="+subordinateRoleByLoginId);
        List<SysRole> sysRoles = new ArrayList<>();
        for (Long id : subordinateRoleByLoginId) {
            SysRole sysRole = roleService.selectByPrimaryKey(id);
            if (sysRole != null) {
                sysRoles.add(sysRole);
            }
        }
        model.addAttribute("roleList", sysRoles);
        return prefix + "add";
    }


    /**
     * 根据 角色id 返回 对应的用户信息
     *
     * @param roleId 角色id
     * @return
     */
    @PostMapping("findUserByRoldId")
    @ResponseBody
    public AjaxResult findUserByRoldId(Long roleId) {
        return AjaxResult.success(userService.findUserNameByRoleId(roleId));
    }


    /**
     * 根据  角色id  返回没有上级的用户 （没有上级用户)
     *
     * @param roleId 角色id
     * @return
     */
    @PostMapping("findOtherPeople")
    @ResponseBody
    public AjaxResult findOtherPeople(Long roleId) {
        List<SysUser> noSuperiorUserByRoleId = userService.findNoSuperiorUserByRoleId(roleId);
        log.info("=================传进来的id是========"+roleId);
        log.info("==========查找到的下属集合=========="+noSuperiorUserByRoleId.toString());
        return AjaxResult.success(noSuperiorUserByRoleId);
    }

    /**
     * 修改页面
     *
     * @return
     */
    @RequestMapping("editBefore")
    public String editBefore(Model model, Long userId) {
        log.info("修改页面=============================" + userId);
        List<SysUserRoles> userRoles = userRolesMapper.selectByUserId(userId);
        //暂时默认一个人只有一个角色 获取角色id
        Long rolesId = userRoles.get(0).getRolesId();
        //根据角色id 返回下属角色id
        Set<Long> peopleByRoleId = findPeopleByRoleId(rolesId);
        List<SysRole> sysRoles = new ArrayList<>();
        for (Long id : peopleByRoleId) {
            SysRole sysRole = roleService.selectByPrimaryKey(id);
            if (sysRole != null) {
                sysRoles.add(sysRole);
            }
        }
        model.addAttribute("roleList", sysRoles);
        return prefix + "edit";
    }

    /**
     * 修改页面的复选框
     *
     * @param roleId 角色id
     * @param userId 用户id
     * @return
     */
    @PostMapping("deitCheck")
    @ResponseBody
    public AjaxResult deitCheck(@RequestParam("roleId") Long roleId, @RequestParam("userId") Long userId) {
        Map<String, Object> map = new HashMap<>();
        List<SysUser> sysUserList2 = new ArrayList<>();
        List<SysUser> noSuperiorUserByRoleId = userService.findNoSuperiorUserByRoleId(roleId);
        QueryWrapper<Relation> relationQueryWrapper2 = new QueryWrapper<>();
        relationQueryWrapper2.eq("parent_id", userId);
        List<Relation> relationList2 = relationService.list(relationQueryWrapper2);
        for (Relation relation : relationList2) {
            sysUserList2.add(userService.selectByPrimaryKey(relation.getUserId()));
        }
        map.put("1", noSuperiorUserByRoleId);
        map.put("2", sysUserList2);
        return AjaxResult.success(map);
    }

    /**
     * 删除
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("delete/{userId}")
    @ResponseBody
    public AjaxResult delect(@PathVariable("userId") Long userId) {
        log.info("userId============================" + userId);
        //删掉 Relation 表中 userId 的信息
        QueryWrapper<Relation> relationQueryWrapper = new QueryWrapper<>();
        relationQueryWrapper.eq("user_id", userId).or().eq("parent_id", userId);
        relationService.remove(relationQueryWrapper);
        return AjaxResult.success();
    }

    /**
     * 批量删除
     *
     * @param userIds 用户id集合
     * @return
     */
    @RequestMapping("deleteAll")
    @ResponseBody
    public AjaxResult delect(@RequestBody List<Long> userIds) {
        //遍历每一个用户
        for (Long userId : userIds) {
            log.info("userId============================" + userId);
            //删掉 Relation 表中 userId 的信息
            QueryWrapper<Relation> relationQueryWrapper = new QueryWrapper<>();
            relationQueryWrapper.eq("user_id", userId).or().eq("parent_id", userId);
            relationService.remove(relationQueryWrapper);
        }
        return AjaxResult.success();
    }


    /**
     * 添加
     *
     * @param listId     下属的id
     * @param roleId     角色的id
     * @param userNameId 角色对应用户的id
     * @return
     */
    @PostMapping("saveMessage")
    @ResponseBody
    public AjaxResult saveMessage(@RequestBody List<Long> listId, String roleId, String userNameId) {

        for (Long id : listId) {
            Relation relation = new Relation();
            relation.setParentId(Long.valueOf(userNameId));
            relation.setUpdateTime(LocalDateTime.now());
            relation.setCreateTime(LocalDateTime.now());
            relation.setUserId(id);
            List<SysRole> sysRoleList = roleService.selectRolesByUserID(id);
            if(!CollectionUtils.isEmpty(sysRoleList)){
                relation.setRoleId(sysRoleList.get(0).getId());
            }
            relationService.save(relation);
        }
        return AjaxResult.success();
    }


    /**
     * 编辑
     *
     * @param listId     下属的id
     * @param roleId     角色的id
     * @param userNameId 角色对应用户的id
     * @return
     */
    @PostMapping("updataMessage")
    @ResponseBody
    public AjaxResult updataMessage(@RequestBody List<Long> listId, String roleId, String userNameId) {
        //先删除 再插入
        QueryWrapper<Relation> relationQueryWrapper = new QueryWrapper<>();
        relationQueryWrapper.eq("parent_id", userNameId);
        relationService.remove(relationQueryWrapper);
        for (Long id : listId) {
            Relation relation = new Relation();
            relation.setParentId(Long.valueOf(userNameId));
            relation.setUpdateTime(LocalDateTime.now());
            relation.setCreateTime(LocalDateTime.now());
            relation.setUserId(id);
            relationService.save(relation);
        }
        return AjaxResult.success();
    }


    /**
     * 展示List页面
     *
     * @return
     */
    @RequestMapping
    public String showListMessage(Model model, SysUser sysUser, Long subordinateId,
                                  @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                  @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize
                                  ) {
        //获取当前登录者的账号
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageInfo = null;
        Long userId = null;
        //这里判断当前用户的是登录者还是它的下属
        if (subordinateId == null) {
            String username = Utility.getCurrentUsername();
            userId = allotService.selectUserIdByUsername(username);
            List<SysUserRoles> userRoles = userRolesMapper.selectByUserId(userId);
            //暂时默认一个人只有一个角色 获取角色id
            Long rolesId = userRoles.get(0).getRolesId();
            pageInfo = userService.findSubordinatesUserByUserID(page, userId, sysUser);
        } else {
            log.info("============进来了======搜索角色名="+sysUser.getUserRole()+"==========搜索用户名"+sysUser.getUsername());
            pageInfo = userService.findSubordinatesUserByUserID(page, subordinateId, sysUser);
            List<SysUser> records = pageInfo.getRecords();
            log.info("=============records===="+records);
            userId = subordinateId;
        }
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        model.addAttribute("userId", userId);
        return prefix + "list";
    }

    /**
     * 展示详情页面
     *
     * @param model
     * @param pageNo   当前页
     * @param pageSize 每页的条数
     * @param userId   用户的id
     * @return
     */
    @RequestMapping("onePeopleMoreMessage")
    public String onePeopleMoreMessage(Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                       @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                       @RequestParam(value = "userId") Long userId, SysUser sysUser) {
        List<SysUserRoles> userRoles = userRolesMapper.selectByUserId(userId);
        //暂时默认一个人只有一个角色 获取角色id
        Long rolesId = userRoles.get(0).getRolesId();
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageInfo = userService.findSubordinatesUserByUserID(page, userId, sysUser);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        model.addAttribute("userId", userId);
        return prefix + "list";

    }

    /**
     * 跟登录者的账号 返回 下属的角色id
     *
     * @return
     */
    public Set<Long> findSubordinateRoleByLoginId() {
        //获取当前登录者的账号
        String username = Utility.getCurrentUsername();
        Long userId = allotService.selectUserIdByUsername(username);
        List<SysUserRoles> userRoles = userRolesMapper.selectByUserId(userId);
        //暂时默认一个人只有一个角色 获取角色id
        Long rolesId = userRoles.get(0).getRolesId();
        //根据角色id 返回下属角色id
        Set<Long> peopleByRoleId = findPeopleByRoleId(rolesId);
        return peopleByRoleId;
    }


    /**
     * 根据角色id 返回 角色的下属的角色id
     *
     * @param roleId
     * @return
     */
    public Set<Long> findPeopleByRoleId(Long roleId) {

        Set<Long> set = new HashSet<>();
        //稿件终审人
        if (roleId.equals(roleCommonEntity.DRAFT_FINAL_REVIEWER)) {
            //板块负责人
            set.add(roleCommonEntity.BLOCK_LEADER);
            set.add(roleCommonEntity.DRAFT_CHECK_LEADER);
            set.add(roleCommonEntity.HANDWRITING_PERSON);
            set.add(roleCommonEntity.DRAFT_CHECKER);
            set.add(roleCommonEntity.SIX_BLOCK);
            set.add(roleCommonEntity.SEVEN_BLOCK);
            //自己
            set.add(roleCommonEntity.DRAFT_FINAL_REVIEWER);

        }
        //版块负责人
        if (roleId.equals(roleCommonEntity.BLOCK_LEADER)) {
            set.add(roleCommonEntity.HANDWRITING_PERSON);
            //自己
            set.add(roleCommonEntity.BLOCK_LEADER);
        }
        //稿件校对组长
        if (roleId.equals(roleCommonEntity.DRAFT_CHECK_LEADER)) {
            set.add(roleCommonEntity.DRAFT_CHECKER);
            //自己
            set.add(roleCommonEntity.DRAFT_CHECK_LEADER);
        }

        //音视频终审人
        if (roleId.equals(roleCommonEntity.AUDIO_VIDEO_FINAL_REVIEWER)) {
            set.add(roleCommonEntity.AUDIO_VIDEO_CHECK_LEADER);
            set.add(roleCommonEntity.AUDIO_ROOFREADER);
            set.add(roleCommonEntity.VIDEO_PROOFREADER);
            set.add(roleCommonEntity.AUDIO_PRODUCER);
            set.add(roleCommonEntity.AUDIO_VISUAL_PRODUCER);
            set.add(roleCommonEntity.PPT_RECORDING_PRODUCER);
            //板块负责人
            set.add(roleCommonEntity.BLOCK_LEADER);
            //自己
            set.add(roleCommonEntity.AUDIO_VIDEO_FINAL_REVIEWER);
        }

        //音视频校对组长
        if (roleId.equals(roleCommonEntity.AUDIO_VIDEO_CHECK_LEADER)) {
            set.add(roleCommonEntity.AUDIO_ROOFREADER);
            set.add(roleCommonEntity.VIDEO_PROOFREADER);
            set.add(roleCommonEntity.AUDIO_PRODUCER);
            set.add(roleCommonEntity.AUDIO_VISUAL_PRODUCER);
            set.add(roleCommonEntity.PPT_RECORDING_PRODUCER);
            set.add(roleCommonEntity.LEARN_CHECK);
            //板块负责人
            set.add(roleCommonEntity.BLOCK_LEADER);
            //自己
            set.add(roleCommonEntity.AUDIO_VIDEO_CHECK_LEADER);
        }
        //音频校对人
        if (roleId.equals(roleCommonEntity.AUDIO_ROOFREADER)) {
            set.add(roleCommonEntity.AUDIO_VISUAL_PRODUCER);
            set.add(roleCommonEntity.AUDIO_PRODUCER);
            //自己
            set.add(roleCommonEntity.AUDIO_ROOFREADER);
        }

        //视频校对人
        if (roleId.equals(roleCommonEntity.VIDEO_PROOFREADER)) {
            set.add(roleCommonEntity.PPT_RECORDING_PRODUCER);
            //自己
            set.add(roleCommonEntity.VIDEO_PROOFREADER);
        }

        //管理员
        if (roleId.equals(roleCommonEntity.ADMINISTRATORS)) {
            //            音视频
            set.add(roleCommonEntity.AUDIO_VIDEO_FINAL_REVIEWER);
            set.add(roleCommonEntity.AUDIO_VIDEO_CHECK_LEADER);
            set.add(roleCommonEntity.AUDIO_ROOFREADER);
            set.add(roleCommonEntity.VIDEO_PROOFREADER);
            set.add(roleCommonEntity.AUDIO_PRODUCER);
            set.add(roleCommonEntity.AUDIO_VISUAL_PRODUCER);
            set.add(roleCommonEntity.PPT_RECORDING_PRODUCER);
            //            稿件
            set.add(roleCommonEntity.DRAFT_FINAL_REVIEWER);
            set.add(roleCommonEntity.DRAFT_CHECK_LEADER);
            set.add(roleCommonEntity.HANDWRITING_PERSON);
            set.add(roleCommonEntity.DRAFT_CHECKER);
            //板块负责人
            set.add(roleCommonEntity.BLOCK_LEADER);
            //自己
            set.add(roleCommonEntity.ADMINISTRATORS);
        }
        //录屏课程负责人
        if (roleId.equals(roleCommonEntity.PPT_RECORDING_RESPONGSIBLE)) {
            set.add(roleCommonEntity.PPT_RECORDING_BROKER);
            //自己
            set.add(roleCommonEntity.PPT_RECORDING_RESPONGSIBLE);
        }
        //录屏课程对接人
        if (roleId.equals(roleCommonEntity.PPT_RECORDING_BROKER)) {
//            set.add(roleCommonEntity.PPT_RECORDING_PRODUCER);
            //自己
            set.add(roleCommonEntity.PPT_RECORDING_BROKER);
        }
        //七队校对组长
        if(roleId.equals(roleCommonEntity.SEVEN_CHECK_LEADER)){
            set.add(roleCommonEntity.SEVEN_CHECK_LEADER);
            set.add(roleCommonEntity.SEVEN_ROOFREADER);
        }
        return set;
    }


}
